import axiosIns, { axiosOdata } from './../utils/axios';
import update, { updateChain } from 'immutability-helper-x';
import { loginData, editData } from '../utils/mock';
import { Modal } from 'antd';
/**
|--------------------------------------------------
| Constants
|--------------------------------------------------
*/
const LOGINING = 'LOGINING';
const LOGINFAIL = 'LOGINFAIL';
const LOGIN = 'LOGIN';
const REGISTERING = 'REGISTERING';
const REGISTERFAIL = 'REGISTERFAIL';
export const REGISTER = 'REGISTER';
const SHOWERRMSG = 'SHOWERRMSG';
const SIGNOUT = 'SIGNOUT';
export const EDITUSERINFO = 'EDITUSERINFO';
const USER_LOADING = 'USER_LOADING';
const OPENAVATAR = 'OPENAVATAR';
const CLOSEAVATAR = 'CLOSEAVATAR';
const UPLOADING = 'UPLOADING';
const UPLOADED = 'UPLOADED';
const RESETPASSWORD = 'RESETPASSWORD';
/**
|--------------------------------------------------
| Actions
|--------------------------------------------------
*/
export function showErrmsg(msg) {
  return {
    type: SHOWERRMSG,
    msg: msg
  };
}
export function login(params) {
  return async (dispatch, getState) => {
    const { auth } = getState().user;
    if (auth.logining) return;
    const res = await axiosIns('/login');
    dispatch(loginSuccess(res.data));
    dispatch(showErrmsg(''));
  };
}
export function loginSuccess(data) {
  initalLogin(data);
  return {
    type: LOGIN,
    userInfo: data.userInfo,
    token: data.token
  };
}
export function register() {
  return async (dispatch, getState) => {
    const { auth } = getState().user;
    if (auth.registering) return;
    // const params = {
    //   phone
    // }
  };
}

export function getUserInfo() {
  return async (dispatch, getState) => {
    const { id } = getState().user.userInfo;
  };
}

export function signout() {
  return {
    type: SIGNOUT
  };
}
/**修改个人信息 */
export function editInfo(params) {
  return async (dispatch, getState) => {
    const { loading } = getState().user;
    if (loading) return;
    dispatch(fetching());
    const res = await axiosIns('/editInfo');
    const { data } = res;
    localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
    dispatch(editInfoed(data));
    dispatch(showErrmsg(''));
  };
}
/**重置密码 */
export function resetPsd({ code, password }) {
  return async (dispatch, getState) => {
    const { loading } = getState().user;
    if (loading) return;
    dispatch(fetching());
    const res = await axiosIns('/resetPsd');
    const { data } = res;
    dispatch(resetPsdSuccess(data));
    dispatch(showErrmsg(''));
  };
}

function editInfoed(data) {
  Modal.success({ title: '修改成功', centered: true });
  return {
    type: EDITUSERINFO,
    userInfo: data.userInfo
  };
}
function initalLogin(data) {
  localStorage.setItem('logged', true);
  localStorage.setItem('userInfo', JSON.stringify(data.userInfo)); //需要保存下次可以获取token的数据
}
function clearLogin() {
  localStorage.removeItem('logged');
  localStorage.removeItem('userInfo');
}

function resetPsdSuccess() {
  return {
    type: RESETPASSWORD
  };
}

export function openAvatar() {
  return {
    type: OPENAVATAR
  };
}

export function closeAvatar() {
  return {
    type: CLOSEAVATAR
  };
}

export function uploadAvatar(params) {
  return async (dispatch, getState) => {
    const { loading } = getState().user.avatarModal;
    if (loading) return;
    dispatch(uploading());
    // const res = axiosIns({ url: '/upload', method: 'POST' })
    const data =
      'http://b2-q.mafengwo.net/s12/M00/E4/A7/wKgED1wizsCAT3NhAAC0dieDtDM66.jpeg?imageMogr2%2Fthumbnail%2F%21200x200r%2Fgravity%2FCenter%2Fcrop%2F%21200x200%2Fquality%2F90';
    setTimeout(() => {
      dispatch(uploadSuccess(data));
    }, 1000);
  };
}
function uploading() {
  return {
    type: UPLOADING
  };
}

function uploadSuccess(data) {
  return {
    type: UPLOADED,
    avatar: data
  };
}

function fetching() {
  console.log('fetching===');
  return {
    type: USER_LOADING
  };
}
/**
|--------------------------------------------------
| Action Handlers
|--------------------------------------------------
*/
const ACTION_HANDLERS = {
  [LOGINING]: (state, action) => {
    return update.$set(state, 'auth.loging', true);
  },
  [LOGIN]: (state, action) => {
    return {
      ...state,
      logged: true,
      userInfo: action.userInfo,
      token: action.token
    };
  },
  [SHOWERRMSG]: (state, action) => {
    return update.$set(state, 'errMsg', action.msg);
  },
  [SIGNOUT]: state => {
    return { ...state, logged: false, userInfo: {} };
  },
  [EDITUSERINFO]: (state, action) => {
    return {
      ...state,
      loading: false,
      userInfo: action.userInfo
    };
  },
  [USER_LOADING]: state => {
    console.log('loading changeing');
    return { ...state, loading: true };
  },
  [OPENAVATAR]: state => {
    return update.$set(state, 'avatarModal.visible', true);
  },
  [CLOSEAVATAR]: state => {
    return update.$set(state, 'avatarModal.visible', false);
  },
  [UPLOADING]: state => {
    return update.$set(state, 'avatarModal.loading', true);
  },
  [UPLOADED]: (state, action) => {
    return updateChain(state)
      .$merge('userInfo', { avatar: action.avatar })
      .$set('avatarModal.loading', false)
      .$set('avatarModal.visible', false)
      .value();
  },
  RESETPASSWORD: (state, action) => {
    return { ...state };
  }
};

/**
|--------------------------------------------------
| Reducer
|--------------------------------------------------
*/

export const initialState = {
  auth: {
    logining: false
  },
  logged: !(
    localStorage.getItem('logged') == null ||
    localStorage.getItem('logged') === 'false'
  ),
  userInfo: JSON.parse(localStorage.getItem('userInfo')),
  // userInfo: {
  //   openid: 'oDOOe4pDDUbN_Wwhg2s_rUfrN8_k',
  //   token: '6D502B088F144C64AA72371F9ADFC526',
  //   clientid: '3ab4528e79044d14aef521255cb5882c'
  // }
  errMsg: '',
  loading: false,
  avatarModal: {
    visible: false,
    loading: false
  }
};

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];
  return handler ? handler(state, action) : state;
}
